package com.example.mutilitemdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Objects;

public class ChatMsgAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final static int CHAT_MSG_TYPE_SEND_TEXT = 0xf1;
    private final static int CHAT_MSG_TYPE_RECV_TEXT = 0xf2;
    private List<ChatMsgModel> list;
    private Context context;

    public void setList(List<ChatMsgModel> list) {
        this.list = list;
    }

    public ChatMsgAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getItemViewType(int position) {
        if (list.get(position).isSendOrRecv())
            return CHAT_MSG_TYPE_SEND_TEXT;
        else return CHAT_MSG_TYPE_RECV_TEXT;
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull  ViewGroup parent, int viewType) {
        switch (viewType){
            case CHAT_MSG_TYPE_SEND_TEXT:
            return new ChatMsgSendHolder(LayoutInflater.from(context).inflate(R.layout.chat_msg_text_send,null));
            default:
                return new ChatMsgRecvHolder(LayoutInflater.from(context).inflate(R.layout.chat_msg_text_recv,null));

        }
    }

    @Override
    public void onBindViewHolder(@NonNull  RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)){
            case CHAT_MSG_TYPE_SEND_TEXT:
                ((ChatMsgSendHolder)holder).sendText.setText(list.get(position).getMsgTextContent());
                ((ChatMsgSendHolder)holder).sendIcon.setImageResource(R.mipmap.ic_launcher);
                break;

            default:
                ((ChatMsgRecvHolder)holder).recvText.setText(list.get(position).getMsgTextContent());
                ((ChatMsgRecvHolder)holder).recvIcon.setImageResource(R.mipmap.ic_launcher);
                break;
        }

    }

    @Override
    public int getItemCount() {
        return null!=list? list.size() : 0;
    }

   class ChatMsgSendHolder extends RecyclerView.ViewHolder {
        ImageView sendIcon;
        TextView sendText;

       public ChatMsgSendHolder(@NonNull View itemView) {
           super(itemView);
           sendIcon=itemView.findViewById(R.id.image_chat_msg_send_icon);
           sendText=itemView.findViewById(R.id.text_msg_send);
       }
   }

   class ChatMsgRecvHolder extends RecyclerView.ViewHolder{
        ImageView recvIcon;
        TextView recvText;

       public ChatMsgRecvHolder(@NonNull View itemView) {
           super(itemView);
           recvIcon=itemView.findViewById(R.id.chat_msg_recv_icon);
           recvText=itemView.findViewById(R.id.text_msg_recv_text);
       }
   }
}
